<template>
  <div>
    <div class="cartheader">
      <div class="container w">
        <div class="header-logo"></div>
        <div class="header-title">
          <h2>我的购物车</h2>
          <p>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</p>
        </div>
      </div>
    </div>
    <div class="hr-20"></div>
    <div class="w mycart">
      <div class="sc-empty" v-show="this.carts.length == 0">
        <span class="icon-minicart"></span>
        <p>您的购物车里什么也没有哦~</p>
        <router-link to="/portal">去逛逛</router-link>
      </div>
      <div class="sc-list" v-show="this.carts.length != 0">
        <div class="sc-pro-title clearfix">
          <div class="label clearfix">
            <a class="choose" @click="ChooseAll()"
              ><i class="iconfont" v-show="!allSelect">&#xe601;</i>
              <i class="iconfont selected" v-show="allSelect">&#xe65c;</i>
            </a>
            <span class="vam">全选<!----></span>
          </div>
          <ul class="clearfix">
            <li>商品</li>
            <li>单价</li>
            <li>数量</li>
            <li>小计</li>
            <li>操作</li>
          </ul>
        </div>
        <div class="sc-pro">
          <div v-for="(item, index) in carts" :key="index">
            <div class="sc-pro-list clearfix">
              <div class="sc-pro-main clearfix">
                <a class="choose" @click="CanselChoose(index)"
                  ><i class="iconfont" v-show="!isCartSelect[index]"
                    >&#xe601;</i
                  >
                  <i class="iconfont selected" v-show="isCartSelect[index]"
                    >&#xe65c;</i
                  >
                </a>
                <router-link
                  :to="{
                    path: '/detail',
                    query: {
                      skuid: item.skuid,
                    },
                  }"
                  class="p-img"
                  ><img
                    :src="`https://img11.360buyimg.com/n7/${cartimg[index][0]}`"
                /></router-link>
                <ul>
                  <li :title="item.jixing">
                    <p class="p-info">
                      {{ item.jixing }}
                      {{ item.color == "0" ? " " : item.color }}
                      {{ item.version == "0" ? "" : item.version }}
                    </p>
                  </li>
                  <li>
                    <div class="p-price">
                      <span>¥&nbsp;{{ item.price }}</span>
                    </div>
                  </li>
                  <li id="elnumber">
                    <el-input-number
                      v-model="item.buynumber"
                      :min="1"
                      :max="10"
                    ></el-input-number>
                  </li>
                  <li class="p-price-total">
                    ¥&nbsp;{{ Math.imul(item.price, item.buynumber) }}
                    <!---->
                  </li>
                  <li>
                    <!-- <a
                      href="javascript:;"
                      class="p-del"
                      @click="deleteOne(item._id, index)"
                      >删除</a
                    > -->
                    <el-popover
                      placement="top"
                      width="160"
                      v-model="isDeletvisible[index]"
                      class="p-del"
                    >
                      <p>是否删除该商品？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button
                          size="mini"
                          type="text"
                          @click="deleteOne(item._id, index, false)"
                          >取消</el-button
                        >
                        <el-button
                          type="primary"
                          size="mini"
                          @click="deleteOne(item._id, index, true)"
                          >确定</el-button
                        >
                      </div>
                      <a slot="reference">删除</a>
                    </el-popover>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div ref="listbottom" style="height: 20px"></div>
      </div>

      <div
        class="w"
        :class="{ sc_total_fixed: fixedcss }"
        v-show="this.carts.length != 0"
      >
        <div class="w sc-total-tool clearfix">
          <div class="sc-total-control">
            <a class="choose" @click="ChooseAll()"
              ><i class="iconfont" v-show="!allSelect">&#xe601;</i>
              <i class="iconfont selected" v-show="allSelect">&#xe65c;</i> </a
            ><a class="vam" @click="ChooseAll()">全选<!----></a>
            <el-popover placement="top" width="160" v-model="visible">
              <p>是否删除所购选的所有商品？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="visible = false"
                  >取消</el-button
                >
                <el-button type="primary" size="mini" @click="DeleteChooseAll"
                  >确定</el-button
                >
              </div>
              <a slot="reference">删除</a>
            </el-popover>
          </div>
          <div class="sc-total-btn">
            <a href="javascript:;" @click="ConfirmCart()">立即结算</a>
          </div>
          <div class="sc-total-price">
            <p>
              <label>总计：</label><span>¥&nbsp;{{ allprice }}.00</span>
            </p>
            <div class="total-choose">
              已选择 <em>{{ allnumber }}</em
              >件商品
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="提示" :visible.sync="noOrdercart" width="30%" center>
      <span style="text-align: center; display: block"
        ><i class="el-icon-warning" style="color:red,margin-right:5px"></i
        >您还没有选择商品哟！</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="noOrdercart = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 1,
      visible: false,
      carts: [],
      isCartSelect: [],
      isDeletvisible: [],
      price: 0,
      fixedcss: true,
      cartimg: [],
      noOrdercart: false,
    };
  },
  computed: {
    allSelect: {
      get: function () {
        let bool = "";
        let j = this.isCartSelect.length;
        let i = 0;
        for (i; i < j; i++) {
          if (this.isCartSelect[i] == false) {
            bool = false;
            break;
          }
          continue;
        }
        if (i >= j) {
          bool = true;
        }
        return bool;
      },
      set: function (val) {
        this.allSelect = val;
      },
    },
    allprice() {
      let allprice = 0;
      for (let i in this.carts) {
        if (this.isCartSelect[i] == true) {
          allprice += Math.imul(this.carts[i].price, this.carts[i].buynumber);
        }
      }
      return allprice;
    },
    allnumber() {
      let allnumber = 0;
      for (let i in this.carts) {
        if (this.isCartSelect[i] == true) {
          allnumber += this.carts[i].buynumber;
        }
      }
      return allnumber;
    },
  },
  methods: {
    getCart() {
      this.axios
        .get("/cart/getCart", {
          params: {
            userid: this.$store.getters.UserInfoID,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.carts = res.data.carts;
            this.carts.forEach((e) => {
              this.cartimg.push(e.imgsrc);
            });
            this.isCartSelect = new Array(this.carts.length).fill(true);
            this.isDeletvisible = new Array(this.carts.length).fill(false);
            this.carts.forEach((c) => {
              this.price += Math.imul(c.price, c.buynumber);
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    deleteOne(id, index, isdelete) {
      if (isdelete) {
        this.axios
          .post("/cart/deleteOne", {
            _id: id,
          })
          .then((res) => {
            if (res.data.code == 200) {
              this.carts.splice(index, 1);
              this.isCartSelect.splice(index, 1);
              this.$set(this.isDeletvisible, index, false);
              this.isDeletvisible.splice(index, 1);
              this.$message({ type: "success", message: "删除成功" });
            } else {
              this.$message({ type: "warning", message: "删除失败" });
            }
          });
      } else {
        this.$set(this.isDeletvisible, index, false);
      }
    },
    CanselChoose(index) {
      this.$set(this.isCartSelect, index, !this.isCartSelect[index]);
    },
    ChooseAll() {
      this.isCartSelect = new Array(this.carts.length).fill(!this.allSelect);
    },
    DeleteChooseAll() {
      this.visible = false;
      //注意删除之后的指正问题，所以从大到小开始删
      for (let i = this.isCartSelect.length - 1; i >= 0; i--) {
        if (this.isCartSelect[i]) {
          this.axios
            .post("/cart/deleteOne", {
              _id: this.carts[i]._id,
            })
            .then(() => {
              this.carts.splice(i, 1);
              this.isCartSelect.splice(i, 1);
              this.$set(this.isDeletvisible, i, false);
              this.isDeletvisible.splice(i, 1);
            });
        }
      }
      // let deletarry = [];
      // for (let i in this.isCartSelect) {
      //   if (this.isCartSelect[i]) {
      //     deletarry.push(i);
      //   }
      // }
      // deletarry.sort((a, b) => {
      //   return b - a;
      // });
      // console.log(deletarry);
      // for (let i in deletarry) {
      // }
    },
    //滚动事件
    handleScroll() {
      //判断元素到浏览器窗口顶部的距离 是否大于视口
      let rect = this.$refs.listbottom.getBoundingClientRect();

      let a =
        rect.top >=
          (window.innerHeight || document.documentElement.clientHeight) ||
        rect.bottom <= 0;

      if (!a) {
        this.fixedcss = false;
      } else {
        this.fixedcss = true;
      }
    },
    //确认订单
    ConfirmCart() {
      let ordercart = [];
      for (let i = 0; i < this.isCartSelect.length; i++) {
        if (this.isCartSelect[i]) {
          ordercart.push(this.carts[i]);
        }
      }
      if (ordercart.length == 0) {
        this.noOrdercart = true;
      } else {
        this.$store.commit("setCarts", {
          cart: ordercart,
          price: this.allprice,
        });
        this.$router.push({
          path: "Confirmcart",
        });
      }
    },
  },
  mounted() {
    setTimeout(() => {
      this.handleScroll();
    }, 200);
    this.getCart();
    // 向页面添加滚动事件
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    //离开这个界面之后，删除滚动事件，不然容易除bug
    window.removeEventListener("scroll", this.handleScroll);
  },
};
</script>

<style scoped>
@import url("../../../assets/fa/css/all.css");
@import url("../../../assets/css/base.css");
@import url("../../../assets/css/shopcart.css");
</style>

<style>
#elnumber .el-input__inner {
  height: 30px;
}
#elnumber .el-input-number {
  width: 110px;
  margin-top: -10px;
  line-height: normal;
}
#elnumber .el-input-number__decrease {
  width: 22px;
  height: 28px;
  line-height: 26px;
}
#elnumber .el-input-number__increase {
  width: 22px;
  height: 28px;
  line-height: 26px;
}
</style>